from time import sleep

from flask import Blueprint, flash, url_for, redirect, render_template
from flask_login import login_user, login_required

from dao import user_dao, mail_dao
from form import forms
from model.user import User

user_bp = Blueprint("user", __name__)


# 用户登录表单
@user_bp.route('/user/login', methods=['GET', 'POST'])
def Login_form():
    Login_form = forms.Login_form()
    if Login_form.validate_on_submit():
        username = Login_form.username.data
        password = Login_form.password.data
        remember = Login_form.remember.data
        # 判断密码是否正确
        user = User.query.filter_by(username=username).first()
        if user and user.password == password:
            # 用户存在时然后密码匹配
            if login_user(user, remember=remember):
                flash('登录成功', category='info')
                # print(current_user.id)
                return redirect(url_for('note.list_note'))
            else:
                flash('用户不存在或密码错误，请重新登录', category='danger')
        else:
            flash('用户不存在或密码错误，请重新登录', category='danger')
    return render_template('Login.html', form=Login_form)


# 用户注册表单
@user_bp.route('/user/register', methods=['GET', 'POST'])
def Register_form():
    Register_form = forms.Register_form()
    if Register_form.validate_on_submit():
        email = Register_form.email.data
        username = Register_form.username.data
        password = Register_form.password.data
        user_dao.registerUser(username, password, email)
        mail_dao.send_register_mail(username,email)
        flash('注册成功')
        sleep(1)
        return redirect(url_for('user.Login_form'))
    else:
        return render_template('Register.html', form=Register_form)



